package com.acme.bankapp.domain.bank;

import com.acme.bankapp.domain.bank.exceptions.NotEnoughFundsException;

import java.io.Serializable;

public abstract class AbstractAccount implements Account, Serializable {
    private double balance;

    public AbstractAccount(final double amount) {
        if (amount < 0) {
            throw new IllegalArgumentException("Negative balance");
        }
        this.balance = amount;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public double getBalance() {
        return balance;
    }

    public abstract double maximumAmountToWithdraw();

    @Override
    public void deposit(final double amount) {
        if (amount < 0) {
            throw new IllegalArgumentException("Negative amount");
        }
        setBalance(getBalance() + amount);
    }

    @Override
    public void withdraw(final double amount) throws NotEnoughFundsException {
        if (amount < 0) {
            throw new IllegalArgumentException("Negative amount");
        }

        if (amount <= (maximumAmountToWithdraw())) {
            setBalance(getBalance() - amount);
        } else {
            throw new NotEnoughFundsException(this, maximumAmountToWithdraw());
        }
    }

    @Override
    public long decimalValue() {
        return Math.round(getBalance());
    }

    @Override
    public String toString() {
        return "balance=" + getBalance();
    }

    @Override
    public int hashCode() {
        long temp = Double.doubleToLongBits(getBalance());
        return (int) (temp ^ (temp >>> 32));
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof AbstractAccount)) return false;

        AbstractAccount that = (AbstractAccount) o;

        if (Double.compare(that.getBalance(), getBalance()) != 0) return false;

        return true;
    }
}
